package com.aiyige.base.api;

import android.text.TextUtils;

import com.aiyige.model.response.BaseResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiachao on 2017/10/23.
 */

public class ApiHelper {
    public static ApiHelper instance;

    public static ApiHelper getInstance() {
        if (instance == null) {
            instance = new ApiHelper();
        }
        return instance;
    }

    public boolean success(Callback callback, Call call, Response response, BaseResponse baseResponse) {
        if (callback == null) {
            return false;
        }
        if (baseResponse != null && baseResponse.hasError() && TextUtils.isEmpty(baseResponse.getMessage())) {
            callback.onFailure(call,new Exception(baseResponse.getMessage()));
            return false;
        }
        if (baseResponse == null || response.body() == null) {
            callback.onFailure(call,new Exception("Srroy,Service Error,Please try again later! responseCode:"+response.errorBody().toString()));
            return false;
        }
        if (TextUtils.isEmpty(response.body().toString()) || baseResponse == null) {
            callback.onFailure(call,new Exception("Srroy,Service Error,Please try again later! responseCode:"+response.code()));
            return false;
        }
        if (baseResponse.hasError()) {
            callback.onFailure(call,new Exception(baseResponse.getMessage()));
            return false;
        }
        if (baseResponse.success()) {
            return true;
        }
        return false;
    }

    public void failed(Callback callback, Call call, Response response, String error) {
        if (response.body() == null || TextUtils.isEmpty(response.body().toString())) {
            callback.onFailure(call,new Exception("Srroy,Service Error,Please try again later! responseCode:"+response.code()
            +"errorDetail:"+error));
        }
    }
}
